import { Button, ConfigProvider, Image, Price } from '@nutui/nutui-react-taro';
import {
  CommonEventFunction,
  ScrollView,
  Swiper,
  SwiperItem,
  SwiperProps,
  Text,
  View,
} from '@tarojs/components';
import Taro from '@tarojs/taro';
import { useCallback, useMemo, useState } from 'react';
import BasicLayout from '@/components/BasicLayout';
import useViewer from '@/hooks/useViewer';
import useQuery from '@/hooks/useQuery';
import gql from 'graphql-tag';
import { GoodsFields } from '@/types/GoodsEntity';
import { OrderEntity, OrderFields } from '@/types/OrderEntity';
import { ShopFields } from '@/types/ShopEntity';
import { UserFields } from '@/types/UserEntity';
import { OrderOnGoodsFields } from '@/types/order-goods.entity';
import useMutation from '@/hooks/useMutation';

const GetSelfOrderQuery = gql`
  query GetSelfOrder{
    getSelfOrder{
      ${OrderFields}
      OrderOnGoods{
        ${OrderOnGoodsFields}
        goods{
          ${GoodsFields}
        }
      }
      shop{
        ${ShopFields}
      }
      user{
        ${UserFields}
      }
    }
  }
`
const DelSelfOrderMutation = gql`
  mutation DelSelfOrder($id:Int!){
    delSelfOrder(id:$id){
      id
    }
  }
`
const ReceivingOrderMutation = gql`
  mutation ReceivingOrder($id:Int!){
    receivingOrder(id:$id){
      id
    }
  }
`
const Order = () => {
  useViewer();
  const { data, refetch } = useQuery(GetSelfOrderQuery)
  const orders: OrderEntity[] = useMemo(() => data?.getSelfOrder || [], [data]);
  const [del] = useMutation(DelSelfOrderMutation, {
    onCompleted() {
      refetch()
    }
  })
  const [receiving] = useMutation(ReceivingOrderMutation, {
    onCompleted() {
      refetch()
    }
  })
  const [tabIndex, setTabIndex] = useState(0);

  const [transtionTime] = useState(100);

  const onChangeTabs = (value: number) => {
    setTabIndex(value);
  };
  const onSwiperAnimationFinish: CommonEventFunction<SwiperProps.onChangeEventDetail> = ({
    detail: { current },
  }) => {
    onChangeTabs(current);
  };
  const onPay = useCallback((order: OrderEntity) => {
    Taro.navigateTo({ url: '/pages/PayOrder/index?id=' + order.id });
  }, [])
  const onDel = useCallback((order: OrderEntity) => {
    del({
      id: order.id
    })
  }, [])
  const onReceiving = useCallback((order: OrderEntity) => {
    receiving({
      id: order.id
    })
  }, [])
  const tabList = ['全部', '待付款', '待配送', '待收货', '已完成'];

  const onOrderDetail = () => {
    // Taro.navigateTo({ url: '/pages/OrderDetail/index' });
  };
  const onComment = useCallback((order: OrderEntity) => {
    Taro.navigateTo({ url: '/pages/Comment/index?id=' + order.id });
  }, [])
  const RenderStatus = useCallback((order: OrderEntity) => {
    if (order.status === "待付款") {
      return (
        <Button onClick={onPay.bind(null, order)} block type="primary" color="#157658">
          去支付
        </Button>
      )
    }
    if (order.status === "已完成") return (
      <View className='flex flex-col gap-1'>
        <Button onClick={onComment.bind(null, order)} block type="danger" color="#157658" >
          评价
        </Button>
        <Button onClick={onDel.bind(null, order)} block type="danger" color="#157658" >
          删除订单
        </Button>
      </View>
    )
    if (order.status === "待收货") return (
      <Button onClick={onReceiving.bind(null, order)} block type="danger" color="#157658" >
        确认收货
      </Button>
    )
    return (
      <View>
      </View>
    )
  }, [])
  const render = useCallback((list: OrderEntity[]) => {
    return list.map((item) => (
      <View key={item.id}>
        <View className="flex flex-col mx-[32rpx] mt-[24rpx] py-[24rpx] px-[16rpx] bg-[#fff] rounded-2">
          {/* 店铺名称 开始 */}
          <View className="flex flex-row">
            <Image src={`http://localhost:14530/media/shop/${item?.shop?.hash_key}/avatar`} width="40" height="40" radius="10rpx" />
            <View className="flex-1 flex justify-between flex-col ml-[20rpx] overflow-hidden">
              <View className="flex-align justify-between">
                <View className="w-76% flex-align">
                  <Text className="w-full text-[28rpx] font-bold color-[#333333] truncate">
                    {item.shop.name}
                  </Text>
                </View>
              </View>
            </View>
          </View>

          {/* 商品内容 开始 */}
          <View className="my-[20rpx] flex flex-row" onClick={onOrderDetail}>
            <View className="w-80%">
              <ScrollView scrollX scrollWithAnimation className="w-full whitespace-nowrap">
                {item.OrderOnGoods?.map((item, index) => (
                  <View
                    key={index}
                    className="w-[200rpx] mr-[20rpx] overflow-hidden inline-block"
                  >
                    <Image src={`http://localhost:14530/media/goods/${item.goods?.hash_key}/avatar`} width="100%" height="75" radius="10rpx" />
                    <View className="mt-[20rpx] text-[28rpx] truncate">{item.goods?.name}</View>
                  </View>
                ))}
              </ScrollView>
            </View>
            <View className="w-20% flex-center flex-col">
              <Price price={((item?.OrderOnGoods?.reduce((count, line) => count + line.count * (line.goods?.price || 0), 0) || 0) + (item?.shop.threshold || 0)) / 100} size="normal" thousands />
              <View className="mt-[8rpx] text-[26rpx] color-[#787878]">
                共<Text className="mx-[8rpx]">{item?.OrderOnGoods?.reduce((count, line) => count + line.count, 0)}</Text>件
              </View>
            </View>
          </View>

          {/* 操作按钮 开始 */}
          <View className="flex justify-end">
            <ConfigProvider
              theme={{
                nutuiButtonSquareBorderRadius: '10rpx',
              }}
            >
              <RenderStatus {...item} />
            </ConfigProvider>
          </View>
        </View>
      </View>
    ))
  }, [])

  const tabListMap = useMemo(() => {
    return tabList.map((status, key) => {
      if (key === 0) return render(orders)
      return render(orders.filter(e => e.status === status))
    });
  }, [orders])




  return (
    <BasicLayout>
      {/* 标签 开始 */}
      <View className="w-full h-[80rpx] flex-center bg-[#fff] border-bottom z-10">
        {tabList.map((item, index) => (
          <View
            key={index}
            className="w-25% h-full flex-center"
            onClick={() => onChangeTabs(index)}
          >
            <Text
              className={`'text-[32rpx] py-[14rpx] border-b-[6rpx] border-b-solid' ${tabIndex === index
                ? 'color-[#157658] border-b-[#157658]'
                : 'color-[#666666] border-b-[#ffffff]'
                }`}
              style={{ transition: `${transtionTime}ms` }}
            >
              {item}
            </Text>
          </View>
        ))}
      </View>

      <View style={{ height: tabListMap[tabIndex].length * 240 + "px" }}>
        <Swiper
          current={tabIndex}
          duration={transtionTime}
          onAnimationFinish={onSwiperAnimationFinish}
          className="h-100%"
        >
          {tabListMap.map((children, key) => (
            <SwiperItem key={key}>
              {children}
            </SwiperItem>
          ))}
        </Swiper>
      </View>
    </BasicLayout>
  );
};

export default Order;
